package cn.itwen.star.graph.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.jwt.JWT;
import cn.itwen.star.graph.core.dto.request.UserLoginReqDTO;
import cn.itwen.star.graph.core.dto.respone.UserLoginResDTO;
import cn.itwen.star.graph.core.mapper.UserMapper;
import cn.itwen.star.graph.core.pojo.User;
import cn.itwen.star.graph.core.service.UserService;
import cn.itwen.star.graph.core.utils.JWTUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.coyote.BadRequestException;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public UserLoginResDTO login(UserLoginReqDTO userLoginReqDTO) throws BadRequestException {
        if (StrUtil.isEmpty(userLoginReqDTO.getUsername())
        || StrUtil.isEmpty(userLoginReqDTO.getPassword())){
            throw new BadRequestException("用户名或密码不能为空");
        }

        User user = lambdaQuery()
                .or(c->c.eq(User::getMobile, userLoginReqDTO.getUsername()))
                .or(c -> c.eq(User::getUsername, userLoginReqDTO.getUsername()))
                .one();

        if (user == null || !BCrypt.checkpw(userLoginReqDTO.getPassword(), user.getPassword())){
            throw new BadRequestException("用户名或密码错误");
        }

        // 生成token
        return generateLoginInfo(user);
    }

    private UserLoginResDTO generateLoginInfo(User user) {
        //拷贝数据
        UserLoginResDTO userLoginResDTO = BeanUtil.toBean(user, UserLoginResDTO.class);
        if(StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getUsername());
        }
        if (StrUtil.isEmpty(userLoginResDTO.getName())){
            userLoginResDTO.setName(user.getMobile());
        }

        String token = JWTUtils.createJWT(user.getId(), userLoginResDTO.getName());
        userLoginResDTO.setToken(token);
        return userLoginResDTO ;
    }
}
